var salt = sessionStorage.getItem('usersalt');
var maxEstimateNum = 0;
var optionType = 0;

   var app = new Vue({
       el:".body",
       data: {
           typeName:[]
       },
       update:function () {

       }
   })
layui.use(['form', 'layer', 'laydate', 'table', 'laytpl'], function () {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laydate = layui.laydate,
        laytpl = layui.laytpl,
        table = layui.table;

    if (!sessionStorage.getItem('username')) {
        layer.msg('请先登录');
        setTimeout("top.location.href='../../../index.html'", 1000);
    }





    form.on('select(questionType)', function (data) {
        optionType = data.value;
        console.log(data.value);
        sortOption();
    });

    form.on('checkbox', function (data) {
        if (data.elem.checked) {
            $(this).siblings(".true").show()
        } else {
            $(this).siblings(".true").hide()
        }
    });

    form.on('radio', function (data) {
        $(".option .true").hide();
        $(this).siblings(".true").show();
    });

    $.post(url + 'question/getTypeName', {Token: salt}, function (data) {
        if(data.code == 0){
            var list = data.data;
            var opt = '<option value="0">请选择</option>'
            for(var i = 0; i < list.length; i++) {
                opt += '<option value="' + list[i].id + '" >' + list[i].name + '</option>'
            }
            $('#typeName').append(opt);
            form.render();
        }else{
            alert(data.msg);
        }
        console.log(data);
    })
    $.post(url + 'question/getDifferServ', {Token: salt}, function (data) {
        if (data.code == 0) {
            var list = data.data;
            var opt = '<option value="">请选择</option>'
            for (var i = 0; i < list.length; i++) {
                opt += '<option value="' + list[i].id + '" >' + list[i].name + '</option>'
            }
            $('#differServ').append(opt);
            form.render();
        } else {
            alert(data.msg);
        }
    })

});

layui.use('upload', function () {
    var $ = layui.jquery,
        upload = layui.upload;

    upload.render({
        elem: '.file',
        url: url + 'attachment/upload',
        multiple: true,
        exts: 'png|jpg|gif|jpeg|PNG|JPG|GIF|JPEG',
        // exts: 'pdf',
        before: function (obj) {
        },
        done: function (res, index) {
            //上传完毕
            if (res.code == 0) {
                var fileId = $(this.item).attr("fileId")?res.data.id:$(this.item).attr("fileId")+","+res.data.id;
                $(this.item).attr("fileId", fileId);
                var img = $('<div style="display:inline-block;position:relative;margin-top:10px;margin-left:20px;" ><div id="'+ res.data.id +'" class="delImg" style="position:absolute;top:-4px;right:-5px;color:white;background:red;border:1px solid red;border-radius:50%;width:16px;height:16px"><i class="layui-icon" style="position:relative;top:0px;right:0px;">&#x1006;</i></div><img id="pic' + res.data.id + '" src="' + url + 'attachment/seekFile/' + res.data.id + '" width="100px" height="100px" class="picsty"/></div>');
                $(this.item).parent().append(img);
            }
        }
    });

});

var checkId = getQueryVariable("id");
var editCompanyId;


var company;

if (checkId != false) {
    $('#id').val(checkId);
    $.ajax({
        url: url + 'risk/getInfo',
        dataType: 'json',
        async: false,
        type: "POST",
        data: {
            Token: salt,
            id: checkId
        },
        success: function (data) {
            if (data.code == 0) {
                initEditItem(data.data);
            } else {
                setTimeout(function () {
                    layer.msg(data.msg);
                }, 1000);
                checkId = false;
                initItemShow();
            }
        },
        error: function (error) {
            console.log("获取失败");
        }
    });
} else {
}



$("body").on("click", ".model .button button", function () {
    $(".model").hide()
});

var letterArr = [];
for (var i = 65, j = 0; i < 91; i++, j++) {
    letterArr[j] = String.fromCharCode(i);
}

//选项排序
sortOption()
function sortOption() {
    $(".option label").each(function (i) {
        $(this).text(letterArr[i]);
    })
    if (optionType == 2) {
        $(".type_option input").hide().siblings().show();
        $(".add_option").hide();
    } else {
        $(".type_option input").show().siblings().hide();
        $(".add_option").show();
    }

    if(optionType == 1){
        $(".option input[type=radio]").attr("type","checkbox");
        $(".option .layui-form-radio").remove()
    }else{
        $(".option input[type=checkbox]").attr("type","radio");
        $(".option .layui-form-checkbox").remove()
    }

    $(".option input[type=checkbox],.option input[type=radio]").prop("checked",false);
    $(".option .true").hide();

    layui.use(['form'], function () {
        var form = layui.form;
        form.render('checkbox');
        form.render('radio')
    });
}

var uploadIndex = 0;

//添加选项
$("body").on("click", ".add_option .box", function () {
    uploadIndex++;
    var input_type = optionType == 1?"checkbox":"radio";
    var str = '<div class="layui-input-block option">' +
        '<label></label><input type="'+input_type+'" name="option" lay-skin="primary">' +
        '<span class="type_option" style="margin-left: 50px;margin-right: 3px;">' +
        '<input type="text" name="title" lay-verify="title" autocomplete="off" placeholder="请输入标题"' +
        'class="layui-input option_input"><span>错误</span></span>' +
        '<i class="seraph icon-guanbi"></i>' +
        '<span class="true">【正解】</span><div><button type="button" class="layui-btn layui-btn-normal file uploadIndex_'+uploadIndex+'">选择图片</button></div>';
    $(".add_option").before(str);
    sortOption();
    layui.use('upload', function () {
        var $ = layui.jquery,
            upload = layui.upload;

        upload.render({
            elem: '.uploadIndex_'+uploadIndex,
            url: url + 'attachment/upload',
            multiple: true,
            exts: 'png|jpg|gif|jpeg|PNG|JPG|GIF|JPEG',
            // exts: 'pdf',
            before: function (obj) {
            },
            done: function (res, index) {
                //上传完毕
                if (res.code == 0) {
                    var fileId = $(this.item).attr("fileId")?res.data.id:$(this.item).attr("fileId")+","+res.data.id;
                    $(this.item).attr("fileId", fileId);
                    var img = $('<div style="display:inline-block;position:relative;margin-top:10px;margin-left:20px;" ><div id="'+ res.data.id +'" class="delImg" style="position:absolute;top:-4px;right:-5px;color:white;background:red;border:1px solid red;border-radius:50%;width:16px;height:16px"><i class="layui-icon" style="position:relative;top:0px;right:0px;">&#x1006;</i></div><img id="pic' + res.data.id + '" src="' + url + 'attachment/seekFile/' + res.data.id + '" width="100px" height="100px" class="picsty"/></div>');
                    $(this.item).parent().append(img);
                }
            }
        });

    });
})

//提交
$("body").on("click", ".commit", function () {
    var differServ = $("#differServ").val();
    var typeName = $("#typeName").val();
    var questionType = $("#questionType").val();
    var title = $("#title").val();
    var fileId = getField($("#fileId"));
    var parse = $("#parse").val();
    var parseFileId = getField($("#parseFileId"));
    var option = [];
    var optionValue;
    if (!differServ || !typeName || !title) {
        alert("请完善内容");
        return
    }
    $(".option").each(function (i) {
        var key = $(this).find("label").text();
        var value = optionType == 2 ? $(this).find(".type_option span").text() : $(this).find(".option_input").val();
        var fileId = getField($(this).find(".file"));
        var answer;
        if(questionType ==  1){
            answer = $(this).find(".layui-form-checkbox").hasClass('layui-form-checked') ? 1 : 0
        }else{
            answer = $(this).find(".layui-form-radio").hasClass('layui-form-radioed') ? 1 : 0
        }
        var obj = {
            key: key,
            value: value,
            fileId: fileId,
            answer:answer
        };
        console.log(obj);
        if (!key || !value) {
            optionValue = false;
            alert("请完善选项内容");
            return
        } else {
            optionValue = true;
        }
        option.push(obj)
    })
    if (!optionValue) {
        return
    }
    if (option.every(function (item) {
            return item.answer == 0
        })) {
        alert("请选择正确选项");
        return
    }
    var sendData = {
        differServ: differServ,
        typeName: typeName,
        questionType: questionType,
        title: title,
        fileId: fileId,
        parse: parse,
        parseFileId: parseFileId,
        options: JSON.stringify(option),
        Token: salt,
    }

    $.post(url + 'question/addQuestion', sendData, function (data) {
        if(data.code == 0){
            layer.alert("新增成功", {
                btn: ['确定'] //按钮
            }, function(index) {
                layer.close(index);
                location.reload();
            });
        }else{
            alert(data.msg);
        }
        console.log(data);
    })


})

//删除选项
$("body").on("click", ".icon-guanbi", function () {
    if ($(".option").length > 2) {
        $(this).parents(".option").remove();
    }
    sortOption()
});

$("body").on("click", ".delImg", function () {
    $(this).parent().remove();
});

function getField($this) {
    var arr = [];
    $this.parent().find(".delImg").each(function () {
        arr.push($(this).attr("id"));
    })
    return arr.length>0?arr.toString():''
}